﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using StartMVC.Models;

namespace StartMVC.Controllers
{
    public class CartController :BaseController
    {
       
        //添加产品项目到购物车,如果没有传入Amount参数则默认数量为1
        [HttpPost]
        public ActionResult AddToCart(int ProductId,int Amount=1)
        {
            //return View();
            var product = db.Products.Find(ProductId);
            if (product==null)
            {
                return HttpNotFound();
            }
            var existingCart = this.Carts.FirstOrDefault(p => p.Product.Id == ProductId);
            if (existingCart != null)
            {
                existingCart.Amount++;
            }
            else
            {
                this.Carts.Add(new Cart() { Product = product, Amount = Amount });
            }
            return new HttpStatusCodeResult(System.Net.HttpStatusCode.Created);
        }


        //显示当前购物车的内容
        public ActionResult Index()
        {
            //return View();
            return View(this.Carts);
        }
        //移除购物车内容
        [HttpPost]
        public ActionResult Remove(int ProductId)
        {
            //return View();
            var existingCart = this.Carts.FirstOrDefault(p => p.Product.Id == ProductId);
            if (existingCart!=null)
            {
                this.Carts.Remove(existingCart);
            }
            return new HttpStatusCodeResult(System.Net.HttpStatusCode.OK);
            
        }
        //更新购物车中特定项目的购买数量
        [HttpPost]
        public ActionResult UpdateAmount(int ProductId,int NewAmount)
        {
            //return View();
            foreach (var item in Carts)
            {
                var existingCart = this.Carts.FirstOrDefault(p => p.Product.Id == item.Product.Id);
                if (existingCart!=null)
                {
                    existingCart.Amount = item.Amount;
                }
            }
            return RedirectToAction("Idex", "Cart");

        }
    }
}
